package top.zhouze.common.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidx.viewbinding.ViewBinding;
import lombok.SneakyThrows;
import top.zhouze.common.util.ReflectUtil;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public abstract class BaseListAdapter<T,V extends ViewBinding> extends BaseAdapter {
    private final List<T> data;
    private Method method;

    protected BaseListAdapter() {
        this.data = new ArrayList<>();
    }

    protected BaseListAdapter(List<T> data) {
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public T getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @SneakyThrows
    @SuppressWarnings("unchecked")
    protected V onBindingView(ViewGroup viewGroup) {
        if (method == null) {
            Class<V> vmCls = ReflectUtil.getGenericClass(this,1);
            method = vmCls.getDeclaredMethod("inflate", LayoutInflater.class);
        }
        return  (V) method.invoke(null, LayoutInflater.from(viewGroup.getContext()));
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        V v = onBindingView(viewGroup);
        if (view == null) {
            view = v.getRoot();
        }
        onBindingData(v,data.get(i),i);
        return view;
    }

    protected abstract void onBindingData(V v, T t, int position);
}